import { mobile } from "@/utils/tools"
import useEventListener from "./useEventListener"
const useTouch = (...args) => {
    let callback = () => void 0
    let offset = 50
    let direction = ""
    let ele = document.body
    for (const arg of args) {
        if (typeof arg === "function") {
            callback = arg
        } else if (typeof arg === "number") {
            offset = arg
        } else if (typeof arg === "string") {
            direction = arg
        } else if (arg instanceof HTMLElement) {
            ele = arg
        }
    }

    let isTouchMove = false
    let touchPageX = 0
    let touchSuccess = false
    let removeEventListener

    useEventListener(ele, "touchstart", (e) => {
        touchPageX = e.touches[0].pageX
        const touchRight = ele.clientWidth - touchPageX < 50
        const touchLeft = touchPageX < 50
        isTouchMove = direction === "left" && touchLeft || direction === "right" && touchRight || (!direction && (touchLeft || touchRight))
        if (isTouchMove && !touchSuccess) {
            removeEventListener = useEventListener(ele, "touchmove", touchMove)
        }
    })

    const touchMove = (e) => {
        //判断e.target是否是untouchable类的子元素或者是untouchable本身
        const ele = Array.from(document.querySelectorAll(".untouchable"))
        //判断e.target是否包含在ele中，或者是ele中某个元素的子元素
        if (ele.some(item => item.contains(e.target) || item === e.target)) {
            return
        }
        
        touchSuccess = Math.abs(touchPageX - e.touches[0].pageX) > 50 && isTouchMove
        if (touchSuccess) {
            callback()
            removeEventListener()
        }
    }

    useEventListener(ele, "touchend", () => {
        isTouchMove = false
        touchSuccess = false
    })
}

const preventDefaultTouch = () => {
    let startX, startY
    useEventListener(document, "touchstart", (e) => {
        startX = e.targetTouches[0].pageX
        startY = e.targetTouches[0].pageY
    }, true)

    useEventListener(document, "touchmove", (e) => {
        let moveX = e.targetTouches[0].pageX
        let moveY = e.targetTouches[0].pageY

        if (Math.abs(moveX - startX) > Math.abs(moveY - startY) && e.cancelable) {
            e.preventDefault()
            e.stopPropagation()
        }
    }, {
        passive: false
    })

    if (mobile) document.oncontextmenu = (e) => {
        e.preventDefault()
        return false
    }
}

const preventDefaultTouchmove = () => {
    return useEventListener(document, "touchmove", (e) => {
        //可以在此对需要侧滑的页面开放权限，注释掉 e.preventDefault()，或者return
        if (e.cancelable) e.preventDefault()
    }, {
        passive: false
    }, true)
}
export default useTouch
export { preventDefaultTouch, preventDefaultTouchmove }